<?php

namespace app\admin\controller;

use app\common\model\ClassKaoqinLog;
use app\common\model\Config;
use app\common\model\ManagerGongzi as ManagerGongziModel;
use app\common\model\ManagerStudent;
use app\common\model\StudentFankui;
use app\common\model\StudentKaoqinRemark as StudentKaoqinRemarkModel;
use app\common\model\MoneyLog as MoneyLogModel;
use app\common\model\OrderShoufei;
use app\common\model\Student as StudentModel;
use app\common\model\Manager as ManagerModel;
use app\common\model\MoneyLog;
use app\common\model\StudentDelay;
use app\common\model\Classes;
use app\common\model\ClassesStu;
use app\common\model\StudentHabit;
use app\common\model\StudentKaoqin;
use app\common\model\StudentKaoqinRemark;
use app\common\model\StudentLog;
use app\common\model\User as UserModel;
use app\common\model\UserStudent;
use app\common\model\User;
use app\common\model\StudentFupan;
use app\common\model\Wenjuan as WenjuanModel;
use app\common\model\WenjuanFankui;
use app\service\LogService;
use app\service\MsgService;
use app\service\StudentService;
use app\service\UserService;
use app\service\WechatService;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
use app\common\model\ManagerGongzi;
use app\common\model\StudentDelete;

class Student extends Base
{

    public $studentLogModel;
    public $studentHabitModel;

    public function __construct()
    {
        parent::__construct();
        $this->studentLogModel = new StudentLog();
        $this->studentHabitModel = new StudentHabit();
    }

    /**
     * 列表
     * @return \think\response\Json
     */
    public function student_list()
    {
        if (request()->isPost()) {
            $data = input('');
            $page = input('page', 1);
            $size = input('size', 10);
            $where = [];
            if ($data['name']) {
                $where['name'] = ['like', "%{$data['name']}%"];
            }
            if ($data['id']) {
                $where['id'] = $data['id'];
            }
            if ($data['cid']) {
                if (!$data['id']) {
                    $where['id'] = array('in', ClassesStu::getColumn(['cid' => $data['cid']], 'sid'));
                }
            }
            // 计算反馈倒计时
            $now_date = date('Y-m',strtotime('-14 days'));

            if($data['is_fankui']){
                $fankui_where = array(
                    'date' => array('eq',$now_date)
                );
                $sids = StudentFankui::getColumn($fankui_where,'sid');
                $where['id'][] = array('not in',$sids);
            }



            $list = StudentService::S()->queryPage($where, $page, $size, '*', 'lose_time asc');
            $total = StudentService::S()->queryCount($where);


            if ($list) {
                $class = Classes::getColumn([], 'id,name');
                foreach ($list as $key => $value) {
                    $list[$key]['cid'] = array_merge(ClassesStu::getColumn(['sid' => $value['id']], 'cid'), []);
                    $classStu = ClassesStu::getAll(['sid' => $value['id']]);
                    if ($classStu) {
                        foreach ($classStu as $v) {
                            $list[$key]['class'][] = $class[$v['cid']];
                        }
                    } else {
                        $list[$key]['class'] = [];
                    }
                    $lose_time = strtotime($value['lose_time']);
                    if (time() < $lose_time) {
                        $list[$key]['day'] = ceil(($lose_time - time()) / 86400);
                    } else {
                        $list[$key]['day'] = 0;
                    }

                    $shoufei_where = array(
                        'sid' => array('=', $value['id'])
                    );
                    $manage = ManagerModel::getColumn([], 'id,name');
                    $shoufei = OrderShoufei::getAll($shoufei_where, 'id desc');
                    if (!$shoufei) {
                        $shoufei = [];
                    } else {
                        foreach ($shoufei as $s => $sv) {
                            $shoufei[$s]['name'] = $manage[$sv['mid']];
                        }
                    }

                    $list[$key]['shoufei'] = $shoufei;

                    $list[$key]['is_fankui'] = StudentFankui::getOne(['sid'=>['eq',$value['id']],'date'=>['eq',$now_date]])?true:false;

                }
            }
            return returnJson(200, '', compact('page', 'size', 'list', 'total'));
        }
    }

    /**
     * 编辑添加
     * @return \think\response\Json
     */
    public function student_edit()
    {
        if (request()->isPost()) {
            $data = input('');
            if (!$data['name']) {
                return returnJson(202, '请填写姓名');
            }
            if (!$data['pay_time']) {
                return returnJson(202, '请填写缴费日期');
            }
            if (!$data['pay_money']) {
                return returnJson(202, '请填写缴费金额');
            }
            if (!$data['month']) {
                $data['month'] = 0;
            }
            if (!$data['send_month']) {
                $data['send_month'] = 0;
            }
            $save_data = [
                'name' => $data['name'],
                'sex' => $data['sex'],
                'birth' => $data['birth'],
                'qiufu_name' => $data['qiufu_name'],
                'update_time' => time(),
                'qiufu_number' => $data['qiufu_number'],
                'warranty' => $data['warranty'],
                'phone' => $data['phone'],
                'jinji' => $data['jinji'],
                'idcard' => $data['idcard'],
                'images' => json_encode($data['images']),
                'month' => $data['month'] ? $data['month'] : 6,
                'send_month' => $data['send_month'] ? $data['send_month'] : 0,
                'pay_time' => strtotime($data['pay_time']),
                'lose_time' => strtotime('+' . $data['month'] + $data['send_month'] . 'month', strtotime($data['pay_time'])),
                'pay_money' => $data['pay_money'],
                'update_time' => time(),
                'tuijian' => $data['tuijian'] ? $data['tuijian'] : '',
                'join_time' => $data['join_time'],
                'class_hour' => $data['class_hour'],
                'has_class_hour' => $data['has_class_hour'],
                'height' => $data['height'],
                'address' => $data['address'],
                'weight' => $data['weight']
            ];


            if ($data['id']) {
                $where = [
                    'id' => $data['id']
                ];
                $student = \app\common\model\Student::getOne($where);
                
                $bind = UserStudent::getAll(['sid' => $data['id']]);
                $sign = false;
                foreach ($student as $key => $value) {
                    if (!$sign && in_array($key, ['month', 'send_month', 'pay_time', 'lose_time', 'pay_money', 'tuijian', 'join_time']) && ($value != $save_data[$key])) {
                        if ($bind) {
                            foreach ($bind as $val) {
                                $user_info = \app\common\model\User::getOne(['id' => $val['uid']]);
                                if ($user_info) {
                                    //发消息 TODO
                                    WechatService::S([
                                        'mall_id' => $user_info['mall_id']
                                    ])->send(
                                        1,
                                        User::uid2openid($user_info['id']),
                                        "【缴费记录】缴费记录发生变化，<a href='http://xy.xiyuezuqiu.cn/m/xiyue/pages/money/index?sid=" . $data['id'] . "'>点此查看</a>"
                                    );
                                }
                            }
                        }
                    }
                }
                $bind_sign = false;
                //成长记录
                $this->studentLogModel->where('sid', $data['id'])->delete();
                if ($data['list_log']) {
                    foreach ($data['list_log'] as $key => $val) {
                        foreach ($val as $log_key => $value) {
                            if ($value === '') {
                                $data['list_log'][$key][$log_key] = null;
                            }
                        }
                        $data['list_log'][$key]['update_time'] = time();
                        $data['list_log'][$key]['create_time'] = time();
                        $data['list_log'][$key]['sid'] = $data['id'];
                        unset($data['list_log'][$key]['id']);
                    }
                    $this->studentLogModel->insertAll($data['list_log']);
                    $bind_sign = true;
                }
                //饮食习惯
                $this->studentHabitModel->where('sid', $data['id'])->delete();
                for ($i = 1; $i < 6; $i++) {
                    if ($data['list_' . $i]) {
                        foreach ($data['list_' . $i] as $key => $val) {
                            $val['create_time'] = time();
                            $val['update_time'] = time();
                            $val['sid'] = $data['id'];
                            unset($val['id']);
                            $data['list_' . $i][$key] = $val;
                        }
                        if ($data['list_' . $i]) {
                            $this->studentHabitModel->insertAll($data['list_' . $i]);
                            $bind_sign = true;
                        }
                    }
                }
                if ($bind && $bind_sign && $data['type'] == 2) {
                    foreach ($bind as $value) {
                        $user_info = \app\common\model\User::getOne(['id' => $value['uid']]);
                        if ($user_info) {
                            //发消息 TODO
                            WechatService::S([
                                'mall_id' => $user_info['mall_id']
                            ])->send(
                                1,
                                User::uid2openid($user_info['id']),
                                "【成长档案】档案发生变化，<a href='http://xy.xiyuezuqiu.cn/m/xiyue/pages/student/index?sid=" . $data['id'] . "'>点此查看</a>"
                            );
                        }
                    }
                }
                $res = StudentService::S()->querySave($save_data, $where);
                $res = $data['id'];
            } else {
                $save_data['create_time'] = time();
                $res = StudentService::S()->querySave($save_data);
            }
            if ($res) {
                ClassesStu::setDel(['sid' => $res]);
                $cids = $data['cid'];
                if ($cids) {
                    foreach ($cids as $cid) {
                        $s_data[] = [
                            'sid' => $res,
                            'cid' => $cid,
                            'create_time' => time(),
                            'update_time' => time()
                        ];
                    }
                    ClassesStu::setSaveAll($s_data);
                }
                $save_data['id'] = $res;
                LogService::S()->writeLog('studentEdit', $this->manager['id'], $save_data);
                return returnJson(200, '编辑成功',$res);

            } else {
                return returnJson(202, '编辑失败');
            }
        }
    }

    /**
     * @return \think\response\Json
     */
    public function del_student()
    {
        $input = input();
        if (!$input['id']) {
            return returnJson(1, 'error');
        }
        $student = StudentModel::getOne(['id' => $input['id']]);
        StudentDelete::setInsertGetId($student);

        \app\common\model\Student::destroy(['id' => $input['id']]);
        ClassesStu::setDel(['sid' => $input['id']]);
        UserStudent::setDel(['sid' => $input['id']]);
        return returnJson(0, '删除成功');
    }

    /**
     * 班级列表
     * @return \think\response\Json
     */
    public function classes_list()
    {
        $data = input('');
        $page = input('page', 1);
        $size = input('size', 20);
        $where = [];
        if ($data['name']) {
            $where['name'] = [
                'like', "%{$data['name']}%"
            ];
        }
        $list = Classes::getPage($where, $page, $size);
        $total = Classes::getCount($where);
        if ($list) {
            foreach ($list as $key => $value) {
                $list[$key]['sid'] = array_merge(ClassesStu::getColumn(['cid' => $value['id']], 'sid'), []);
                if ($list[$key]['sid']) {
                    $list[$key]['s_lst'] = \app\common\model\Student::getPage(['id' => ['in', $list[$key]['sid']]]);
                } else {
                    $list[$key]['s_lst'] = [];
                }
            }
        } else {
            $list = [];
        }
        return returnJson(200, '', compact('list', 'total', 'page', 'size'));
    }

    /**
     * 全部学员
     * @return \think\response\Json
     */
    public function all_student_list()
    {

        $where = array();
        $data = input('');
        if ($data['cid']) {
            if (!$data['id']) {
                $where['id'] = array('in', ClassesStu::getColumn(['cid' => $data['cid']], 'sid'));
            }
        }
        $list = \app\common\model\Student::getAll($where, 'name desc', 'id,name');
        if (!$list) {
            $list = [];
        }
        return returnJson(200, '', $list);
    }

    /**
     * 全部班级
     * @return \think\response\Json
     */
    public function all_classes_list()
    {
        $list = \app\common\model\Classes::getAll([], '', 'id,name,week');
        if (!$list) {
            $list = [];
        }
        return returnJson(200, '', $list);
    }

    /**
     * 编辑班级
     * @return \think\response\Json
     */
    public function classes_edit()
    {
        $data = input('');
        if (!$data['name']) {
            return returnJson(202, '请填写班级名称');
        }
        $save_data = [
            'name' => $data['name'],
            'week' => $data['week'],
            'update_time' => time()
        ];
        if ($data['id']) {
            $res = Classes::update($save_data, ['id' => $data['id']]);
            if ($res) {
                if ($data['sid']) {
                    ClassesStu::setDel(['cid' => $data['id']]);
                    foreach ($data['sid'] as $val) {
                        $stu_data[] = [
                            'sid' => $val,
                            'cid' => $data['id'],
                            'update_time' => time(),
                            'create_time' => time()
                        ];
                    }
                    ClassesStu::setSaveAll($stu_data);
                }
                return returnJson(200, '编辑成功');
            } else {
                return returnJson(202, '编辑失败');
            }
        } else {
            $save_data['create_time'] = time();
            $res = Classes::setInsertGetId($save_data);
            if ($res) {
                foreach ($data['sid'] as $val) {
                    $stu_data[] = [
                        'sid' => $val,
                        'cid' => $res,
                        'update_time' => time(),
                        'create_time' => time()
                    ];
                }
                if ($stu_data)
                    ClassesStu::setSaveAll($stu_data);
                return returnJson(200, '添加成功');
            } else {
                return returnJson(202, '添加失败');
            }
        }
    }

    /**
     * 收费
     * @return \think\response\Json
     */
    public function shoufei()
    {
        $data = input('');
        if (!$data['money']) {
            return returnJson(202, '请填写收费金额');
        }
        $save_data = [
            'money' => $data['money'],
            'sid' => $data['sid'],
            'has_class_hour' => $data['has_class_hour'],
            'order_sn' => create_order_sn($data['sid'], 'SF'),
            'mid' => $this->manager['id'],
            'update_time' => time()
        ];
        if ($data['id']) {
            $res = OrderShoufei::update($save_data, ['id' => $data['id']]);
            if ($res) {
                return returnJson(200, '编辑成功');
            } else {
                return returnJson(202, '编辑失败');
            }
        } else {
            $save_data['create_time'] = time();
            $shoufei_where = [
                'sid' => array('=', $data['sid']),
                'checked' => array('=', 0),
            ];

            OrderShoufei::update(['checked' => 2], $shoufei_where);
            $res = OrderShoufei::setInsertGetId($save_data);
            if ($res) {
                $shoufei_where = [
                    'sid' => array('=', $data['sid'])
                ];
                $manage = ManagerModel::getColumn([], 'id,name');
                $shoufei = OrderShoufei::getAll($shoufei_where, 'id desc');
                if (!$shoufei) {
                    $shoufei = [];
                } else {
                    foreach ($shoufei as $s => $sv) {
                        $shoufei[$s]['name'] = $manage[$sv['mid']];
                    }
                }
                return returnJson(200, '添加成功', $shoufei);
            } else {
                return returnJson(202, '添加失败');
            }
        }
    }

    /**
     * 全部班级学员
     * @return \think\response\Json
     */
    public function all_classes_stu_list()
    {
        $where = array();
        $data = input('');
        if ($data['cid'] || $data['cid'] === 0) {
            $where['id'] = $data['cid'];
        }
        $list = Classes::getAll($where, '', 'id,name');
        if ($list) {
            foreach ($list as $key => $value) {
                $sids = ClassesStu::getColumn(['cid' => $value['id']], 'sid');
                $list[$key]['s_lst'] = \app\common\model\Student::getAll(['id' => ['in', $sids]], 'name asc', 'id,name');
            }
        }
        return returnJson(200, '', $list);
    }

    /**
     *
     * @return \think\response\Json
     */
    public function del_classes()
    {
        $input = input();
        if (!$input['id']) {
            return returnJson(1, 'error');
        }
        Classes::destroy(['id' => $input['id']]);
        ClassesStu::setDel(['cid' => $input['id']]);
        return returnJson(0, '删除成功');
    }

    public function delay()
    {
        if (request()->isPost()) {
            $cid = input('cid');
            if ($cid) {
                if (input('type') == 2) {
                    $sids = ClassesStu::getColumn(['cid' => $cid], 'sid');
                } else {
                    $sids = input('cid');
                }
                if ($sids) {
                    $list = \app\common\model\Student::getAll(['id' => ['in', $sids]]);
                    $delay_data = [];
                    foreach ($list as $value) {
                        $delay_data[] = [
                            'day' => input('day'),
                            'sid' => $value['id'],
                            'desc' => input('desc'),
                            'create_time' => time(),
                            'update_time' => time()
                        ];
                        $save_data['lose_time'] = $value['lose_time'] + input('day') * 24 * 60 * 60;
                        \app\common\model\Student::update($save_data, ['id' => $value['id']]);
                    }
                    StudentDelay::setSaveAll($delay_data);
                    return returnJson(200, '延期成功');
                }
            }
        }
    }

    /**
     * 考勤记录
     * @return \think\response\Json
     */
    public function scorelog()
    {
        if (request()->isPost()) {

            if ($this->mall_id != 0) {
                $where['mall_id'] = $this->mall_id;
            }
            $input = input();
            if ($input['sid']) {
                $where['sid'] = $input['sid'];
            }
            if ($input['time']) {
                $where['time'] = array('like',$input['time'].'%');
            }
            if ($input['manager_name']) {
                $where['manager_name'] = $input['manager_name'];
            }
            if ($input['cid']) {
                $where['sid'] = array('in', ClassesStu::getColumn(['cid' => $input['cid']], 'sid'));
            }
            if ($input['update_time']) {
                $where['time'] = array(
                    ['>=', $input['update_time'][0]],
                    ['<=', $input['update_time'][1]],
                );
            }
            $page = max($input['page'], 1);
            $size = 20;
            $all = 0;

            if ($input['excel']) {
                $list = StudentKaoqin::getGroupby($where, $page, 10000, 'time asc', '*', 'thumb');
                $total = StudentKaoqin::getGroupByCount($where, 'thumb');
            }else{
                $list = StudentKaoqin::getGroupby($where, $page, $size, 'id desc', '*', 'thumb');
                $total = StudentKaoqin::getGroupByCount($where, 'thumb');
            }

            if (!$list) {
                return returnJson(0, '', [
                    'list' => [],
                    'size' => $size,
                    'total' => 0
                ]);
            }
            foreach ($list as $k => $v) {
                $stu_list_sid_where = array(
                    'content' => $v['content'],
                    'thumb' => $v['thumb']
                );
                $stu_list_sid = StudentKaoqin::getColumn($stu_list_sid_where, 'sid');
                $stu_list = [];
                if ($stu_list_sid) {
                    $stu_list = StudentModel::getColumn(['id' => ['in', $stu_list_sid]], 'id,name,create_time');
                }
                $list[$k]['stu_list'] = $stu_list;
                $list[$k]['total'] = sizeof($stu_list);
                $all += $list[$k]['total'];

                $list[$k]['classesInfo'] = Classes::getAll(['id' => ['in', $v['cid']]], 'id desc', 'id,name,create_time');
                //班级内全部学生
                $class_stu = ClassesStu::getAll(['cid' => ['in', $v['cid']]], 'cid desc', 'sid,cid');
                //未出勤学生
                $weichuqin_sids = [];
                if ($class_stu && $v['cid']) {
                    foreach ($class_stu as $s) {
                        if (!in_array($s['sid'], $stu_list_sid))
                            $weichuqin_sids[] = $s['sid'];
                    }
                    $wcq_stu_list = StudentModel::getColumn(['id' => ['in', $weichuqin_sids]], 'id,name,create_time');
                    $wcq_remark_sids = StudentKaoqinRemarkModel::getColumn(['img' => ['eq', $v['thumb']]], 'sid');
                    $jishu=0;
                    foreach ($wcq_stu_list as $wkk => $wv) {
                        $wcq_stu_list[$wkk]['coach_status'] = in_array($wv['id'], $wcq_remark_sids) ? false : true;
                        if($wcq_stu_list[$wkk]['coach_status'])
                            $jishu++;
                    }

                    $list[$k]['wcq_stu_list'] = $wcq_stu_list;
                    $list[$k]['weibeizhu'] = $jishu;
                } else {
                    $list[$k]['wcq_stu_list'] = [];
                }
            }
            if ($input['excel']) {
                //导出excel
                if (!$list) {
                    return returnJson(1, '无数据');
                }
                if (!($input['update_time'])) {
                    return returnJson(1, '必须选择一个上课时间区间');
                }
                if(ceil(((strtotime($input['update_time'][1])-strtotime($input['update_time'][0]))/(24*3600)))>15)
                    return returnJson(1, '时间跨度不要超过15天');
                $file = $this->exportKaoqin($list);
                return returnJson(0, '', $file);
            }
            return returnJson(0, '', [
                'list' => $list,
                'size' => $size,
                'total' => $total,
                'page' => $page,
                'all' => $all
            ]);
        }
    }

    public function kaoqin()
    {
        $input = input();
        if (!$input['note']) {
            return returnJson(1, '请填写备注');
        }
        if (!$input['time']) {
            return returnJson(1, '请选择上课时间');
        }
        if (!$input['thumb']) {
            return returnJson(1, '请上传考勤图片');
        }
        if (!$input['sids']) {
            return returnJson(1, '请选择学员');
        }

//        $key = "charge-0-{$input['number']}";
//        $cache = cache($key);
//        if ($cache) {
//            return returnJson(1, '为防止重复充值,请1分钟后再试');
//        }
//        cache($key, 1, 60);
        $all = [];
        $time = time();
        foreach ($input['sids'] as $value) {
            foreach ($value as $val) {
                $userStu = UserStudent::getOne(['sid' => $val]);
                if ($userStu) {
                    $all[] = [
                        'uid' => $userStu['uid'],
                        'sid' => $val,
                        'create_time' => $time,
                        'update_time' => $time,
                        'content' => $input['note'],
                        'mall_id' => 1,
                        'manager_name' => $this->manager['name'],
                        'thumb' => $input['thumb'],
                        'time' => $input['time'],
                        'cid' => $input['cid']
                    ];
                } else {
                    $all[] = [
                        'uid' => 0,
                        'sid' => $val,
                        'create_time' => time(),
                        'update_time' => time(),
                        'content' => $input['note'],
                        'mall_id' => 1,
                        'manager_name' => $this->manager['name'],
                        'thumb' => $input['thumb'],
                        'time' => $input['time'],
                        'cid' => $input['cid']

                    ];
                }
            }
        }
        if ($input['bukesids']) {
            foreach ($input['bukesids'] as $val) {
                $userStu = UserStudent::getOne(['sid' => $val]);
                if ($userStu) {
                    $all[] = [
                        'uid' => $userStu['uid'],
                        'sid' => $val,
                        'create_time' => $time,
                        'update_time' => $time,
                        'content' => $input['note'],
                        'mall_id' => 1,
                        'manager_name' => $this->manager['name'],
                        'thumb' => $input['thumb'],
                        'time' => $input['time']
                    ];
                } else {
                    $all[] = [
                        'uid' => 0,
                        'sid' => $val,
                        'create_time' => time(),
                        'update_time' => time(),
                        'content' => $input['note'],
                        'mall_id' => 1,
                        'manager_name' => $this->manager['name'],
                        'thumb' => $input['thumb'],
                        'time' => $input['time']

                    ];
                }
            }
        }
        if ($all) {
            $log = [];
            foreach ($all as $value) {
                $d = StudentKaoqin::setInsertGetId($value);
                $student = studentModel::getOne(['id' => $value['sid']]);
                studentModel::setFieldInc(['id' => $value['sid']], 'has_class_hour');//消除课时
                $student1 = studentModel::getOne(['id' => $value['sid']]);
                $add['type'] = 'kaoqin';
                $add['info'] = $this->manager['id'];
                $add['data'] = json_encode(['input' => $input, 'student_old' => $student, 'student_new' => $student1]);
                $add['create_time'] = date('Y-m-d H:i:s');
                $add['api'] = $_SERVER['REQUEST_URI'];
                $add['remark'] = $value['sid'];
                $log[] = $add;
            }

            if ($log) {
                LogService::S()->writeLogs($log);
            }

        }
        $kaoqin = array(
            'cid' => $input['cid'],
            'mid' => $this->manager['id'],
            'update_time' => $time,
            'create_time' => $time,
            'time' => $input['time'],
            'thumb' => $input['thumb']
        );
        $r = ClassKaoqinLog::setInsertGetId($kaoqin);

        $g_where = array(
            'mid' => $this->manager['id'],
            'time' => $input['time'],
        );
        ManagerGongzi::gongziUpdate($g_where);
        return returnJson(0, '考勤成功');
    }



    public function remark()
    {
        $input = input();
        if (!$input['remark']) {
            return returnJson(1, '请填写备注');
        }
        if (!$input['thumb']) {
            return returnJson(1, '请上传考勤图片');
        }
        $where = [
            'id' => ['eq', $input['kid']]
        ];
        $kaoqin = StudentKaoqin::getOne($where);
        $time = time();
        $save = [
            'update_time' => $time,
            'create_time' => $time,
            'cid' => $kaoqin['cid'],
            'time' => $kaoqin['time'],
            'sid' => $input['sid'],
            'remark' => $input['remark'],
            'thumb' => $input['thumb'],
            'img' => $kaoqin['thumb']
        ];
        StudentKaoqinRemark::setInsertGetId($save);
        return returnJson(0, '备注成功');
    }

    function delKaoqin()
    {
        $input = input();
        $where = array();
        if ($input['thumb']) {
            $where['thumb'] = array('=', $input['thumb']);
        }
        if ($where) {
            $list = StudentKaoqin::getColumn($where, 'sid');
            if ($list) {
                $log = [];
                foreach ($list as $value) {
                    $student = studentModel::getOne(['id' => $value]);
                    StudentModel::setFieldDec(['id' => array('eq', $value)], 'has_class_hour', 1);
                    $student1 = studentModel::getOne(['id' => $value]);
                    $add['type'] = 'delKaoqin';
                    $add['info'] = $this->manager['id'];
                    $add['data'] = json_encode(['input' => $input, 'student_old' => $student, 'student_new' => $student1]);
                    $add['create_time'] = date('Y-m-d H:i:s');
                    $add['api'] = $_SERVER['REQUEST_URI'];
                    $add['remark'] = $value['sid'];
                    $log[] = $add;
                }
                LogService::S()->writeLogs($log);
            }

            StudentKaoqin::setDel($where);
            ClassKaoqinLog::setDel($where);


        }
        return returnJson(0, '删除考勤成功');
    }

    function kaoqinLogNew()
    {
        // 上一月
        
        $l_y = date('m')==1?date('Y')-1:date('Y');
        $l_m = date('m')==1?12:date('m')-1;
        $l_m = $l_m<10?'0'. $l_m:$l_m;
        $l_d = date('t',strtotime($l_y . '-' . $l_m . '-1'));//上一月最后一天
        $last = $l_y . '年' . $l_m . '月';

        // 班级信息
        $class = $list_s = $list = array();
        $classes = Classes::getColumn([], 'id,week,name');
        foreach ($classes as $value) {
            $class[$value['week']][] = $value['id'];
        }

        $l_w = date('w',strtotime($l_y . '-' . $l_m . '-' . '1'));
        $l_w = $l_w==0?7:$l_w;
        for($i=1;$i<$l_w;$i++){
            $list_s[] = [
                'w' => '',
                'd' => '',
                'date' => '',
                'log' => ''
            ];
        }

        for($i=1;$i<=$l_d;$i++){
            $date = date('Y-m-d', strtotime($l_y . '-' . $l_m . '-' . $i));
            $w = date('w', strtotime($date));
            $w = $w == 0 ? 7 : $w;
            $where = [
                'time' => ['=', $date],
            ];
            $kaoqin = ClassKaoqinLog::getColumn($where, 'cid');
            $cl = [];
            if ($class[$w]) {
                foreach ($class[$w] as $c) {
                    if (!in_array($c, $kaoqin)) {
                        $cl[] = $classes[$c];
                    }
                }
            }
            $list_s[] = [
                'w' => $w,
                'd' => $i,
                'date' => $date,
                'log' => $cl
            ];
        }

        // 当前月份
        $y = date('Y');
        $m = date('m');
        $d = date('d');
        $now = $y . '年' . $m . '月';
        $w = date('w',strtotime($y . '-' . $m . '-' . '1'));
        $w = $w==0?7:$w;
        for($i=1;$i<$w;$i++){
            $list[] = [
                'w' => '',
                'd' => '',
                'date' => '',
                'log' => ''
            ];
        }
        for($i=1;$i<=$d;$i++){
            $date = date('Y-m-d', strtotime($y . '-' . $m . '-' . $i));
            $w = date('w', strtotime($date));
            $w = $w == 0 ? 7 : $w;
            $where = [
                'time' => ['=', $date],
            ];
            $kaoqin = ClassKaoqinLog::getColumn($where, 'cid');
            $cl = [];
            if ($class[$w]) {
                foreach ($class[$w] as $c) {
                    if (!in_array($c, $kaoqin)) {
                        $cl[] = $classes[$c];
                    }
                }
            }
            $list[] = [
                'w' => $w,
                'd' => $i,
                'date' => $date,
                'log' => $cl
            ];
        }

        return returnJson(200, '', compact('list_s','list','last','now'));


    }

    function kaoqinLog()
    {
        $y = date('Y');
        $d = date('d');
        $m = date('m');
        $log = [];
        if ($d < 28) {
            if ($m == 1) {
                $y--;
                $m = 12;
            } else {
                $m--;
            }
            if (in_array($m, [1, 3, 5, 7, 8, 10, 12])) {
                $log = array_merge(range(31 - 27 + $d, 31), range(1, $d));
            } else if ($m == 2) {
                if (($y % 4 == 0 && $y % 100 != 0) || ($y % 400 == 0)) {
                    $log = array_merge(range(29 - 27 + $d, 29), range(1, $d));
                } else {
                    $log = array_merge(range(28 - 27 + $d, 28), range(1, $d));
                }
            } else {

                $log = array_merge(range(30 - 27 + $d, 30), range(1, $d));
            }
        } else {
            $log = range($d - 27, $d);
        }
        $list = $class = $list_h = $list_q = [];
        $classes = Classes::getColumn([], 'id,week,name');
        foreach ($classes as $value) {
            $class[$value['week']][] = $value['id'];
        }
        foreach ($log as $key => $vlaue) {
            if ($key && ($vlaue < $log[$key - 1])) {
                if ($m == 12) {
                    $m = 1;
                    $y++;
                } else {
                    $m++;
                }
            }
            $date = date('Y-m-d', strtotime($y . '-' . $m . '-' . $vlaue));
            $w = date('w', strtotime($date));
            $w = $w == 0 ? 7 : $w;
            $where = [
                'time' => ['=', $date],
            ];
            $kaoqin = ClassKaoqinLog::getColumn($where, 'cid');
            $cl = [];
            if ($class[$w]) {
                foreach ($class[$w] as $c) {
                    if (!in_array($c, $kaoqin)) {
                        $cl[] = $classes[$c];
                    }
                }
            }


            $list[] = [
                'w' => $w,
                'd' => $vlaue,
                'date' => $date,
                'log' => $cl
            ];
        }
        $w = $list[0]['w'];
        $date = $list[0]['date'];
        if ($w != 1) {
            for ($i = 0; $i < $w - 1; $i++) {
                $list_q[] = [
                    'w' => $i,
                    'date' => date('Y-m-d', strtotime($date) - ($w - $i - 1) * 24 * 3600),
                    'd' => '',
                    'log' => []
                ];
            }
        }
        $w = $list[27]['w'];
        $date = $list[27]['date'];
        if ($w != 7) {
            for ($w = $w + 1; $w < 8; $w++) {
                $list_h[] = [
                    'w' => $w,
                    'date' => date('Y-m-d', strtotime($date) + (8 - $w) * 24 * 3600),
                    'd' => '',
                    'log' => []
                ];
            }

        }
        $list = array_merge($list_q, $list, $list_h);
        $l = [];
        foreach ($list as $k => $v) {
            $l[ceil(($k + 1) / 7) - 1][] = $v;
        }
        return returnJson(200, '', $l);

    }

    function tingke()
    {
        $input = input();
        $time = time();
        if ($input['cid']) {
            $kaoqin = array(
                'cid' => $input['cid'],
                'mid' => $this->manager['id'],
                'update_time' => $time,
                'create_time' => $time,
                'time' => $input['time'],
                'status' => 1
            );
            ClassKaoqinLog::setInsertGetId($kaoqin);
        }

        return returnJson(200, '考勤成功');
    }


    /**
     * 列表
     * @return \think\response\Json
     */
    public function fupan_list()
    {
        $where = array();
        if (input('name', ''))
            $where['name'] = array('like', "%" . input('name', '') . "%");
        $page = max(input('page'), 1);
        $size = 20;
        $list = StudentFupan::getPage($where, $page, $size);
        $total = StudentFupan::getCount($where);
        if (!$list) {
            $list = [];
            return returnJson(0, '', compact('list', 'total', 'page', 'size'));
        }
        return returnJson(0, '', [
            'list' => $list,
            'size' => $size,
            'total' => $total,
            'page' => $page
        ]);
    }

    /**
     * 复盘
     */
    public function fupan(){
        $save = input('');
        if(request()->isPost()){
            $time = time();
            $save['update_time'] = $time;
            $save['create_time'] = $time;
            $save['mid'] = $this->manager['id'];
            StudentFupan::setInsertGetId($save);

            return returnJson(0, '操作成功');
        }
        return returnJson(1, '网络异常，请重试');
    }

    /**
     * 反馈
     */
    public function fankui(){
        $save = input('');
        if(request()->isPost()){
            $time = time();
            $save['update_time'] = $time;
            $save['create_time'] = $time;
            $save['mid'] = $this->manager['id'];
            if($save['type'] == 2){
                $date = date('Y-m');
            }else{
                $now_y = date('Y');
                $now_m = date('m');
                if($now_m==1){
                    $m = 12;
                    $y = $now_y-1;
                }else{
                    $m = $now_m-1;
                    $y = $now_y;
                }
                $date = date('Y-m',strtotime("{$y}-{$m}-01"));
            }
            $save['date'] = $date;
            unset($save['type']);
            StudentFankui::setInsertGetId($save);

            return returnJson(1, '操作成功');
        }
        return returnJson(0, '网络异常，请重试');
    }

    /**
     * 本月训练信息
     */
    public function xunlian(){
        $save = input('');
        if(request()->isPost()){
            //训练次数
            $start = date('Y-m-01',strtotime('-14 days'));
            $end = date('Y-m-t',strtotime('-14 days'));
            $where = array(
                'time' => array(array('>=',$start),array('<=',$end)),
                'sid' => array('eq',$save['sid'])
            );
            $count = StudentKaoqin::getCount($where);

            $s_where = array(
                'id' => array('eq',$save['sid'])
            );
            $student = StudentModel::getOne($s_where);
            //年龄
            $birth = $student['birth'];
            $birth = str_replace('年','-',$birth);
            $birth = str_replace('月','-',$birth);
            $birth = str_replace('日','',$birth);
            $bm = getMonthNum($birth,$start);
            $age = ceil($bm/12);

            if($save['type'] == 2){
                $date = date('Y-m');
            }else{
                $now_y = date('Y');
                $now_m = date('m');
                if($now_m==1){
                    $m = 12;
                    $y = $now_y-1;
                }else{
                    $m = $now_m-1;
                    $y = $now_y;
                }
                $date = date('Y-m',strtotime("{$y}-{$m}-01"));
            }

            //球龄
            $jm = getMonthNum($student['join_time'],$start);
            $qiuling = floor($jm/12)?floor($jm/12) . '年':'';
            $qiuling .= ($jm%12)?($jm%12). '月':'';

            return returnJson(0, '操作成功',compact('count','age','qiuling','date'));
        }
        return returnJson(1, '网络异常，请重试');
    }

    protected function exportKaoqin($list)
    {
        $spreadsheet = new Spreadsheet();
        $sheet = $spreadsheet->getActiveSheet();
        $arrData = [
            ['日期', '班级', '人数', '教练', '备注', '考勤不通过']
        ];
        foreach ($list as $k => $v) {
            $banji = $v['classesInfo']?$v['classesInfo'][0]['name']:'';
            $weibeizhu = $v['weibeizhu']?$v['weibeizhu'] . '人未备注':'';
            $arrData[] = [
                $v['time'],$banji, $v['total'], $v['manager_name'], $v['content'], $weibeizhu
            ];
        }

        $sheet->fromArray($arrData, NULL);
        $writer = new Xlsx($spreadsheet);
        $name = '考勤信息-' . date('Y-m',strtotime($list[0]['time']))  . ".xlsx";
        $path = ROOT_PATH . "public" . DS . "cache" . DS . $name;
        $writer->save($path);
        return request()->domain() . "/cache/" . $name;
    }



}

